// var createError = require('http-errors');
var express = require('express');
var path = require("path")
var fs = require("fs")
var multer = require("multer")
var app = express();

// view engine setup
// app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, 'public')));


// 静态资源
app.use(express.static("./"));
app.use(express.static("./public/js"));
app.use(express.static("./public/upload"));

// 上传文件
app.use(multer({dest: "/luoyao/"}).array("myFile"));


app.post('/upload',function (req,res) {
  var obj = req.body;
  // console.log(req);
  // console.log(req.files[0]);
  var file = req.files[0]
  // console.log(file);
  var time = +new Date();
    var name = file.originalname;
    var imgName = time+"_"+name;
    var destFile = "./public/upload/" + imgName;
    var path = file.path;
    fs.readFile(path, function(err, data) {
        if(err) {
            console.log(err);
        } else {
            // console.log(data);
            fs.writeFile(destFile, data, function(err) {
                if(err) {
                    console.log(err);
                    res.send(JSON.stringify({error: 2}));
                } else {
                    var obj = {
                        msg: 0,
                        result: {
                            name: name,
                            time: time,
                            src: imgName
                        }
                    }
                    res.send(JSON.stringify({data: obj}));
                }
            })
        }
    })
  

})




app.get("/",function (req,res) {
  // res.send(__dirname+"/jQupLoad.html")
  res.sendFile(path.join(__dirname,"./jQupLoad.html"))
})

app.listen(82,function () {
  console.log("server is run  82");
  
})

module.exports = app;
